package com.example.springbootproject.redis;


import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.hash.Jackson2HashMapper;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

@Component
public class RedisTest {


    @Autowired
    RedisTemplate redisTemplate; // high level operation

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    ObjectMapper objectMapper;

    public void testRedis(){
//        redisTemplate.opsForValue().set("hello","china");
//        Object hello = redisTemplate.opsForValue().get("hello");
//        System.out.println(hello);

        stringRedisTemplate.opsForValue().set("hello01","nihao");
        String hello01 = stringRedisTemplate.opsForValue().get("hello01");
        System.out.println(hello01);


        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
        connection.set("hello02".getBytes(),"lili".getBytes());
        System.out.println(new String(Objects.requireNonNull(connection.get("hello02".getBytes()))));

        HashOperations<String, Object, Object> hash = stringRedisTemplate.opsForHash();
        hash.put("sean","name","lss");
        hash.put("sean","age","22");
        System.out.println(hash.entries("sean"));


        Person person = new Person();
        person.setName("zhangsan");
        person.setAge(23);

        // flatten 是否扁平化 即一个对象中包含对象【展示的时候是扁平展示还是原格式展示】
        Jackson2HashMapper jackson2HashMapper = new Jackson2HashMapper(objectMapper, false);
        redisTemplate.opsForHash().putAll("testHash", jackson2HashMapper.toHash(person));
        Map testHash = redisTemplate.opsForHash().entries("testHash");
        Person person1 = objectMapper.convertValue(testHash, Person.class);
        System.out.println(person1.getName() +" "+person1.getAge());

        redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));


    }

}
